package xin.marcher.module.lifecycle.mq.consumer.listener;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xin.marcher.module.common.constants.RocketDelayedLevel;
import xin.marcher.module.common.enums.lifecycle.ProductStageEnum;
import xin.marcher.module.common.enums.lifecycle.ProductStatusEnum;
import xin.marcher.module.common.enums.message.BinlogType;
import xin.marcher.module.common.exception.BaseBizException;
import xin.marcher.module.common.exception.ProductErrorCodeEnum;
import xin.marcher.module.common.message.DataChangeMessage;
import xin.marcher.module.common.utils.JsonUtil;
import xin.marcher.module.construction.domain.dto.ItemDetailDTO;
import xin.marcher.module.construction.domain.dto.ItemInfoDTO;
import xin.marcher.module.lifecycle.domain.dto.ItemPeriodStageDTO;
import xin.marcher.module.lifecycle.domain.request.ItemPeriodRequest;
import xin.marcher.module.lifecycle.domain.request.ItemPeriodStatusRequest;
import xin.marcher.module.lifecycle.mq.producer.DefaultProducer;
import xin.marcher.module.lifecycle.remote.ProductRemote;
import xin.marcher.module.lifecycle.service.ItemPeriodStageService;
import xin.marcher.module.lifecycle.service.ItemPeriodStatusService;

import java.util.List;
import java.util.Objects;

/**
 * 监听建品 & 修改商品topic，修改生命周期中维护的商品状态和生命周期
 */
@Slf4j
@Component
public class ItemUpdateListener implements MessageListenerConcurrently {

    @Autowired
    private ProductRemote productRemote;

    @Autowired
    private ItemPeriodStageService itemPeriodStageService;

    @Autowired
    private ItemPeriodStatusService itemPeriodStatusService;

    @Autowired
    private DefaultProducer defaultProducer;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
            for (MessageExt messageExt : list) {
                log.info("商品变更，消息内容：{}", messageExt.getBody());
                String msg = new String(messageExt.getBody());

                DataChangeMessage tableDataChangeMessage = JsonUtil.json2Object(msg, DataChangeMessage.class);
                if (Objects.isNull(tableDataChangeMessage)) {
                    throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
                }

                String itemId = getItemId(tableDataChangeMessage);
                // 商品建品同步默认状态和生命周期
                if (tableDataChangeMessage.getAction().equals(BinlogType.INSERT.getValue())) {
                    List<ItemDetailDTO> itemDetailList = getItemDetailList(itemId);
                    if (CollectionUtils.isNotEmpty(itemDetailList)) {
                        ItemDetailDTO itemDetailDTO = itemDetailList.get(0);
                        ItemInfoDTO itemInfoDTO = itemDetailDTO.getItemInfoDTO();
                        ItemPeriodRequest stageRequest = new ItemPeriodRequest();
                        stageRequest.setItemId(itemId);
                        stageRequest.setItemName(itemInfoDTO.getItemName());
                        stageRequest.setCategoryId(itemInfoDTO.getCategoryId());
                        itemPeriodStageService.saveItemPeriodStage(stageRequest);
                    }
                }

                // 修改商品状态
                if (tableDataChangeMessage.getAction().equals(BinlogType.UPDATE.getValue())) {
                    List<ItemDetailDTO> itemDetailList = getItemDetailList(itemId);
                    if (CollectionUtils.isNotEmpty(itemDetailList)) {
                        ItemDetailDTO itemDetailDTO = itemDetailList.get(0);

                        ItemInfoDTO itemInfo = itemDetailDTO.getItemInfoDTO();
                        // 商品状态
                        ItemPeriodStatusRequest statusRequest = new ItemPeriodStatusRequest();
                        statusRequest.setItemId(itemId);
                        statusRequest.setItemName(itemInfo.getItemName());
                        statusRequest.setItemStatus(itemInfo.getItemStatus());
                        itemPeriodStatusService.updateItemStatus(statusRequest);

                        // 生命周期阶段
                        Integer stage = getPeriodStage(itemInfo.getItemStatus());

                        ItemPeriodStageDTO itemPeriodStageDTO = new ItemPeriodStageDTO();
                        itemPeriodStageDTO.setItemId(itemId);
                        itemPeriodStageDTO.setPeriodStage(stage);
                        itemPeriodStageService.updateProductPeriod(itemPeriodStageDTO);
                    }
                }

                // 发送回调消息
                defaultProducer.sendMessage(tableDataChangeMessage.getCallbackTopic(),
                        tableDataChangeMessage.getMessageNo(), RocketDelayedLevel.DELAYED_1m, "表变更消息处理完成返回延迟消息");
            }
        } catch (Exception e) {
            log.error("consume error, 商品缓存更新失败", e);
            // 本次消费失败，下次重新消费
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    /**
     * 获取商品状态和生命周期状态的对应关系
     *
     * @param itemStatus
     * @return
     */
    private Integer getPeriodStage(Integer itemStatus) {
        if (Objects.isNull(itemStatus)) {
            throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
        }

        if (itemStatus.equals(ProductStatusEnum.PRE_ON_MARKET.getCode())) {
            return ProductStageEnum.NEW.getCode();
        }

        if (itemStatus.equals(ProductStatusEnum.TRY_SALE_ON_MARKET.getCode())) {
            return ProductStageEnum.TRY_SALE.getCode();
        }

        if (itemStatus.equals(ProductStatusEnum.PUT_ON_THE_MARKET.getCode())) {
            return ProductStageEnum.GROWN.getCode();
        }

        if (itemStatus.equals(ProductStatusEnum.PRE_EXIT_THE_MARKET.getCode())) {
            return ProductStageEnum.PRE_ELIMINATE.getCode();
        }

        if (itemStatus.equals(ProductStatusEnum.EXIT_THE_MARKET.getCode())) {
            return ProductStageEnum.ELIMINATED.getCode();
        }

        if (itemStatus.equals(ProductStatusEnum.STOP_SALE.getCode())) {
            return ProductStageEnum.ELIMINATED.getCode();
        }

        return -1;
    }

    /**
     * 获取商品信息
     *
     * @param itemId
     * @return
     */
    private List<ItemDetailDTO> getItemDetailList(String itemId) {
        ItemPeriodStatusRequest request = new ItemPeriodStatusRequest();
        request.setItemId(itemId);
        return productRemote.listItems(request);
    }

    /**
     * 拿到itemId
     *
     * @param tableDataChangeMessage
     * @return
     */
    private String getItemId(DataChangeMessage tableDataChangeMessage) {
        Object keyId = tableDataChangeMessage.getKeyId();
        if (Objects.isNull(keyId)) {
            throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
        }
        return String.valueOf(keyId);
    }
}
